package com.wnhz.work.jy.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.bean.TakeGold.GoodsBean;
import com.wnhz.work.jy.bean.TakeGold.LevelTwoBean;
import com.wnhz.work.jy.bean.TakeGold.TakeGoldBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.MyUtils;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;
import com.wnhz.work.jy.view.SwitchView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TakeGoldActivity extends BaseActivity implements View.OnClickListener, TextWatcher, SwitchView.OnStateChangedListener {

    private static final int SET_ADDRESS_REQUESTCODE = 540;
    private static final int SET_BANK_REQUESTCODE = 550;
    private static final int SET_GOODADDR_REQUESTCODE = 560;
    private static final int SET_GOODNAMES = 241;
    private static final int SET_NUM = 41;
    private static final int SET_BANK_REQUESTCODE1 = 411;
    private static final int SET_BANK_REQUESTCODE2 = 412;
    private static final int SET_BANK_REQUESTCODE3 = 413;
    private static final int PAY_PASSWORK = 999;

    private String province;
    private String city;
    private String area;
    private TextView title;
    private String shop_name_tv;
    private TextView gold_tv;//金币
    private TextView address_tv;//地区
    private TextView shop_mame;//店铺
    private TextView time_tv;//时间
    private TextView gold_number_tv;//数量
    private int way = 0;//0自取 1配送

    private View mode;
    private View reserve_information;
    private View time_lay;
    private View rl_address;

    private TextView tv_addr;
    private String name;
    private String addressId;
    private String phone;
    private String citys;
    private String areas;
    private String doorplate;
    private String addr;

    private TakeGoldBean takeGoldBean;

    private ArrayList<String> goodNumbers = new ArrayList<>();
    private ArrayList<String> nums = new ArrayList<>();

    private String goodsName;
    private String shop;
    private int goodsName_index = -1;
    private int shop_index;
    private int num = -1;

    private View next_step;
    private View ll_choose_web;

    private TextView zh, fh, fcl;

    private String zhonghang, zhihang, fenchuli;

    private List<LevelTwoBean> level3 = new ArrayList<>();
    ArrayList<GoodsBean> glist;
    private EditText name_tv, id_card_tv, phone_number, code_tv;
    private String goodstr;
    private Button get_code;
    private String phoneNumber;

    private TextView address_name, address_phone, toast;
    private String addressname;


    private int time = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 12:
                    if (time == 0) {
                        get_code.setFocusable(true);
                        if (MyUtils.isMobileNO(phoneNumber)) {
                            get_code.setSelected(true);
                        } else {
                            get_code.setSelected(false);
                        }
                        get_code.setText("获取验证码");
                    } else {
                        time--;
                        get_code.setSelected(false);
                        get_code.setText("获取验证码" + time);
                        handler.sendEmptyMessageDelayed(12, 1000);
                    }

                    break;
            }
        }
    };

    private SwitchView switchButton;
    private View line;
    private LinearLayout ll_invoice;
    private EditText et_invoice;
    private String invoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_gold);
        glist = (ArrayList<GoodsBean>) getIntent().getSerializableExtra("list");
        initTirle();
        initView();
        initClick();
        name_tv.setFocusable(true);
        name_tv.setFocusableInTouchMode(true);
        name_tv.requestFocus();
        reserve_information.setVisibility(View.GONE);
        //getData();
        next_step.setVisibility(View.GONE);
        onClick(findViewById(R.id.post));

        int n = 0;
        for (int i = 0; i < glist.size(); i++) {
            n += glist.get(i).getMyNum();
            if (i == 0) {
                goodstr = glist.get(i).getGoodId() + ":" + glist.get(i).getMyNum();
            } else {
                goodstr = goodstr + "," + glist.get(i).getGoodId() + ":" + glist.get(i).getMyNum();
            }
        }
        gold_tv.setText("您选择了" + n + "件商品");
    }

    private void initView() {
        address_name = (TextView) findViewById(R.id.name);
        address_phone = (TextView) findViewById(R.id.tv_phone);
        toast = (TextView) findViewById(R.id.toast);

        get_code = (Button) findViewById(R.id.get_code);
        name_tv = (EditText) findViewById(R.id.name_tv);
        phone_number = (EditText) findViewById(R.id.phone_number);
        code_tv = (EditText) findViewById(R.id.code_tv);
        id_card_tv = (EditText) findViewById(R.id.id_card_tv);
        mode = findViewById(R.id.mode);
        ll_choose_web = findViewById(R.id.ll_choose_web);
        reserve_information = findViewById(R.id.reserve_information);
        time_lay = findViewById(R.id.time_lay);
        rl_address = findViewById(R.id.rl_address);
        gold_tv = (TextView) findViewById(R.id.gold_tv);
        address_tv = (TextView) findViewById(R.id.address);
        time_tv = (TextView) findViewById(R.id.time_tv);
        tv_addr = (TextView) findViewById(R.id.tv_addr);
        gold_number_tv = (TextView) findViewById(R.id.gold_number);
        next_step = findViewById(R.id.next_step);
        zh = (TextView) findViewById(R.id.zh);
        fh = (TextView) findViewById(R.id.fh);
        fcl = (TextView) findViewById(R.id.fcl);
        phone_number.addTextChangedListener(this);
        switchButton = (SwitchView) findViewById(R.id.switchButton);
        line = findViewById(R.id.line);
        ll_invoice = (LinearLayout) findViewById(R.id.ll_invoice);
        et_invoice = (EditText) findViewById(R.id.et_invoice);

        switchButton.setOpened(false);
        switchButton.setOnStateChangedListener(this);

    }

    private void initClick() {
        findViewById(R.id.next_step).setOnClickListener(this);
        findViewById(R.id.select_gold).setOnClickListener(this);
        rl_address.setOnClickListener(this);
        time_lay.setOnClickListener(this);
        get_code.setOnClickListener(this);
        findViewById(R.id.ask_for).setOnClickListener(this);
        findViewById(R.id.post).setOnClickListener(this);
        findViewById(R.id.gold_number_lay).setOnClickListener(this);
        findViewById(R.id.ll_choose_1).setOnClickListener(this);
        findViewById(R.id.ll_choose_2).setOnClickListener(this);
        findViewById(R.id.ll_choose_3).setOnClickListener(this);
    }

    private void initTirle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("提金币");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
    }

    private String code;

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //下一步
            case R.id.next_step:
                phoneNumber = phone_number.getText().toString();
                card = id_card_tv.getText().toString();
                name = name_tv.getText().toString();
                code = code_tv.getText().toString();
                if (name == null || "".equals(name)) {
                    MyToast("请输入姓名");
                    break;
                } else if (card == null || "".equals(card) || !MyUtils.isIDCard(card)) {
                    MyToast("请输入正确身份证号");
                    break;
                }/*else if (phoneNumber == null || "".equals(phoneNumber)){
                    MyToast("请输入手机号");
                    break;
                }else if (!MyUtils.isMobileNO(phoneNumber)){
                    MyToast("请输入正确手机号");
                    break;
                }*/ else if (addressId == null || "".equals(addressId)) {
                    MyToast("请选择地址");
                    break;
                }/*else if (!phoneNumber.equals(oldphone)){
                    MyToast("请输入获取验证码的手机号");
                    break;
                }else if (code == null && !"".equals(code)){
                    MyToast("请输入验证码");
                    break;
                }else if (!code.equals(first_code)){
                    MyToast("请输入正确验证码");
                    break;
                }*/ else {
                    intent = new Intent(this, InPutPayPassWordActivity.class);
                    intent.putExtra("type", 2);
                    startActivityForResult(intent, PAY_PASSWORK);
                }
                break;

            //选择金币
            case R.id.select_gold:
                /*if (goodNames.size() == 0){
                    return;
                }*/
                //startActivity(new Intent(this, SelectGold.class));
                /*startActivityForResult(new Intent(this, SelectShopBranchActivity.class).putExtra("list", goodNames), SET_GOODNAMES);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);*/
                break;
            case R.id.gold_number_lay:
                if (goodsName_index == -1) {
                    MyToast("请先选择金币");
                    return;
                }
                nums.clear();
                for (int i = 1; i < Integer.parseInt(goodNumbers.get(goodsName_index)) + 1; i++) {
                    nums.add(i + "");
                }
                startActivityForResult(new Intent(this, SelectShopBranchActivity.class).putExtra("list", nums), SET_NUM);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                break;

            //选择地址
            case R.id.rl_address:
//                startActivityForResult(new Intent(this, SetAdressActivity.class), SET_ADDRESS_REQUESTCODE);
//                overridePendingTransition(R.anim.push_up_in,R.anim.push_up_out);
                intent = new Intent(TakeGoldActivity.this, ChooseAddressActivity.class);
                startActivityForResult(intent, SET_GOODADDR_REQUESTCODE);
                break;

            //选择店铺
           /* case R.id.shop_lay:
                startActivityForResult(new Intent(this, SelectShopBranchActivity.class).putExtra("list", shops), SET_BANK_REQUESTCODE);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                *//*startActivityForResult(new Intent(this, SelectShopBranchActivity.class).putExtra("list", list), SET_BANK_REQUESTCODE);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);*//*
                break;*/

            //选择时间
            case R.id.time_lay:

                break;

            //自取
            case R.id.ask_for:
                way = 0;
                mode.setVisibility(View.GONE);
                reserve_information.setVisibility(View.VISIBLE);
                if (way == 0) {
                    time_lay.setVisibility(View.VISIBLE);
                    rl_address.setVisibility(View.GONE);
                } else {
                    time_lay.setVisibility(View.GONE);
                    rl_address.setVisibility(View.VISIBLE);
                }
                ll_choose_web.setVisibility(View.VISIBLE);
                next_step.setVisibility(View.VISIBLE);
                break;

            //邮寄
            case R.id.post:
                way = 1;
                mode.setVisibility(View.GONE);
                reserve_information.setVisibility(View.VISIBLE);
                if (way == 0) {
                    time_lay.setVisibility(View.VISIBLE);
                    rl_address.setVisibility(View.GONE);
                } else {
                    time_lay.setVisibility(View.GONE);
                    rl_address.setVisibility(View.VISIBLE);
                }
                next_step.setVisibility(View.VISIBLE);
                ll_choose_web.setVisibility(View.GONE);
                break;
            case R.id.get_code:
                phoneNumber = phone_number.getText().toString();
                if (MyUtils.isMobileNO(phoneNumber)) {
                    if (time == 0) {
                        get_code.setFocusable(false);
                        getCode();
                    }

                }

                break;
           /* case R.id.ll_choose_1:
                ArrayList<String> list = new ArrayList<>();
                list.add(branchBean.getLevelone().getBranchName());
                Log.e(TAG, "onClick: "+list.get(0) );
                startActivityForResult(new Intent(this, SetBankActivity.class).putExtra("list", list), SET_BANK_REQUESTCODE1);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                break;
            case R.id.ll_choose_2:
                ArrayList<String> list2 = new ArrayList<>();
                for (int i = 0; i < branchBean.getLevelTwo().size(); i++) {
                    list2.add(branchBean.getLevelTwo().get(i).getBranchname());
                }
                startActivityForResult(new Intent(this, SetBankActivity.class).putExtra("list", list2), SET_BANK_REQUESTCODE2);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                break;
            case R.id.ll_choose_3:
                if (fh_index != -1) {
                    if (last_zh_index != fh_index) {
                        last_zh_index = fh_index;
                        getlevelThree();
                    } else {
                        setFCL();
                    }

                }


                break;*/
        }
    }


    private void setFCL() {
        ArrayList<String> list3 = new ArrayList<>();
        for (int i = 0; i < level3.size(); i++) {
            list3.add(level3.get(i).getBranchname());
        }
        startActivityForResult(new Intent(this, SetBankActivity.class).putExtra("list", list3), SET_BANK_REQUESTCODE3);
        overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
    }


    private int last_zh_index = -2;


    private int zh_index = -1;
    private int fh_index = -1;
    private int fcl_index = -1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SET_NUM:
                    num = Integer.parseInt(data.getStringExtra("bank_name"));
                    gold_number_tv.setText(num + "");
                    break;
                case SET_ADDRESS_REQUESTCODE:
                    province = data.getStringExtra("province");
                    city = data.getStringExtra("city");
                    area = data.getStringExtra("area");
                    address_tv.setText(city + "-" + area);
                    break;
                case SET_BANK_REQUESTCODE:
                    shop_name_tv = data.getStringExtra("bank_name");
                    shop_index = data.getIntExtra("index", 0);
                    shop_mame.setText(shop_name_tv);
                    break;
                case SET_GOODADDR_REQUESTCODE:
                    addressId = data.getStringExtra("addressId");
                    addressname = data.getExtras().getString("name");
                    phone = data.getExtras().getString("phone");
                    citys = data.getExtras().getString("city");
                    areas = data.getExtras().getString("area");
                    doorplate = data.getExtras().getString("doorplate");
                    address_phone.setText(phone);
                    address_name.setText(addressname);
                    addr = citys + areas + doorplate;
                    toast.setVisibility(View.GONE);

                    tv_addr.setText(addr);
                    break;
                case SET_GOODNAMES:
                    goodsName = data.getStringExtra("bank_name");
                    goodsName_index = data.getIntExtra("index", 0);
                    gold_tv.setText(goodsName);
                    if (Integer.parseInt(goodNumbers.get(goodsName_index)) < num) {
                        num = 0;
                        gold_number_tv.setText("0");
                    }
                    break;
                case SET_BANK_REQUESTCODE1:
                    if (resultCode == RESULT_OK) {
                        zhonghang = data.getStringExtra("bank_name");
                        zh_index = data.getIntExtra("index", 0);
                        zh.setText(zhonghang);
                    }
                    break;
                case SET_BANK_REQUESTCODE2:
                    if (resultCode == RESULT_OK) {
                        zhihang = data.getStringExtra("bank_name");
                        fh_index = data.getIntExtra("index", 0);
                        fh.setText(zhihang);
                    }
                    break;
                case SET_BANK_REQUESTCODE3:
                    fenchuli = data.getStringExtra("bank_name");
                    fcl_index = data.getIntExtra("index", 0);
                    fcl.setText(fenchuli);
                    break;
                case PAY_PASSWORK:
                    String pay_passwork = data.getStringExtra("passwork");
                    post(pay_passwork);
                    break;

            }
        }


    }

    private static final String TAG = "TakeGoldActivity";
    private String oldphone;
    private String codetime;
    private String first_code;

    private void getCode() {
        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);
        showDialog();
        XUtil.Post(ConfigUtil.GETPAYYZM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: code  " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if ("1".equals(re)) {
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        oldphone = jsonObject1.optString("phone");
                        codetime = jsonObject1.optString("time");
                        first_code = jsonObject1.optString("code");
                        time = 60;
                        handler.sendEmptyMessage(12);
                    } else {
                        get_code.setFocusable(true);
                        String info = jsonObject.optString("info");
                        Toast.makeText(TakeGoldActivity.this, info, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    private String card;
    private String realname;

    private void post(String pay_passwork) {
        invoice = et_invoice.getText().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", MyApplication.getInstance().userBean.getUserId());
        map.put("goodstr", goodstr);
        map.put("addressId", addressId);
        map.put("realname", name);
        map.put("card", card);
        map.put("mobile", phone);
        map.put("payPass", pay_passwork);
        map.put("message", invoice);
        Log.d(TAG, "post: " + goodstr);
        showDialog();
        XUtil.Post(ConfigUtil.GOLDADD, map, new MyCallBack<String>() {

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if ("1".equals(re)) {
                        startActivity(new Intent(TakeGoldActivity.this, MyMain.class));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

        phoneNumber = phone_number.getText().toString();
        if (MyUtils.isMobileNO(phoneNumber)) {
            get_code.setSelected(true);
        } else {
            get_code.setSelected(false);
        }
    }

    @Override
    public void toggleToOn(View view) {
        switchButton.setOpened(true);
        line.setVisibility(View.VISIBLE);
        ll_invoice.setVisibility(View.VISIBLE);
    }

    @Override
    public void toggleToOff(View view) {
        switchButton.setOpened(false);
        line.setVisibility(View.GONE);
        ll_invoice.setVisibility(View.GONE);
        et_invoice.setText("");
    }
}
